package cn.schoolwow.quickdao.module.entity.flow.scan;

import cn.schoolwow.quickdao.annotation.TableName;
import cn.schoolwow.quickdao.domain.QuickDAOConfig;
import cn.schoolwow.quickdao.domain.entity.Entity;
import cn.schoolwow.quickdao.util.StringUtil;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;

import java.util.Map;

public class ScanEntityClassFlow implements BusinessFlow {

    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        QuickDAOConfig quickDAOConfig = flowContext.checkInstanceData(QuickDAOConfig.class);

        Map<Class, String> entityClassMap = quickDAOConfig.entityOption.entityClassMap;
        for (Class entityClass : entityClassMap.keySet()) {
            Entity entity = new Entity();
            if (entityClass.getDeclaredAnnotation(TableName.class) != null) {
                entity.tableName = ((TableName) entityClass.getDeclaredAnnotation(TableName.class)).value();
            } else if (entityClassMap.get(entityClass).isEmpty()) {
                entity.tableName = StringUtil.camel2Underline(entityClass.getSimpleName());
            } else {
                entity.tableName = entityClassMap.get(entityClass) + "@" + StringUtil.camel2Underline(entityClass.getSimpleName());
            }
            entity.clazz = entityClass;
            quickDAOConfig.databaseContext.entityMap.put(entityClass.getName(), entity);
        }
    }

    @Override
    public String name() {
        return "扫描指定实体类";
    }

}
